from flask import render_template, redirect, url_for, flash, request, current_app
from flask_login import login_required, current_user
from routes import design_bp
from extensions import db
from models import Design
from forms.design import DesignForm
from utils.helpers import save_image
import os
import json

@design_bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    category = request.args.get('category')
    keyword = request.args.get('keyword')
    sort = request.args.get('sort', 'newest')

    query = Design.query

    if category:
        query = query.filter_by(category=category)
    if keyword:
        query = query.filter(Design.title.contains(keyword) | 
                           Design.description.contains(keyword))

    if sort == 'newest':
        query = query.order_by(Design.created_at.desc())
    elif sort == 'popular':
        query = query.order_by(Design.likes.desc())
    elif sort == 'views':
        query = query.order_by(Design.views.desc())

    designs = query.paginate(page=page, per_page=9, error_out=False)
    return render_template('design/index.html', designs=designs)

@design_bp.route('/create', methods=['GET', 'POST'])
@login_required
def create():
    form = DesignForm()
    if form.validate_on_submit():
        design = Design(
            title=form.title.data,
            category=form.category.data,
            description=form.description.data,
            content=form.content.data,
            tags=form.tags.data,
            user_id=current_user.id
        )

        if form.cover_image.data:
            cover_image = save_image(form.cover_image.data, 'designs/covers')
            design.cover_image = url_for('static', filename=f'uploads/designs/covers/{cover_image}')

        if form.images.data:
            image_urls = []
            for image in form.images.data:
                if image.filename:
                    saved_image = save_image(image, 'designs/images')
                    image_urls.append(url_for('static', filename=f'uploads/designs/images/{saved_image}'))
            design.images = ','.join(image_urls)

        db.session.add(design)
        db.session.commit()
        flash('设计案例发布成功！', 'success')
        return redirect(url_for('design.detail', id=design.id))

    return render_template('design/create.html', form=form)

@design_bp.route('/<int:id>')
def detail(id):
    design = Design.query.get_or_404(id)
    design.views += 1
    db.session.commit()
    return render_template('design/detail.html', design=design)

@design_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit(id):
    design = Design.query.get_or_404(id)
    if design.user_id != current_user.id:
        flash('您没有权限编辑此设计案例！', 'danger')
        return redirect(url_for('design.detail', id=id))

    form = DesignForm(obj=design)
    if form.validate_on_submit():
        design.title = form.title.data
        design.category = form.category.data
        design.description = form.description.data
        design.content = form.content.data
        design.tags = form.tags.data

        if form.cover_image.data:
            cover_image = save_image(form.cover_image.data, 'designs/covers')
            design.cover_image = url_for('static', filename=f'uploads/designs/covers/{cover_image}')

        if form.images.data:
            image_urls = []
            for image in form.images.data:
                if image.filename:
                    saved_image = save_image(image, 'designs/images')
                    image_urls.append(url_for('static', filename=f'uploads/designs/images/{saved_image}'))
            if image_urls:
                design.images = ','.join(image_urls)

        db.session.commit()
        flash('设计案例更新成功！', 'success')
        return redirect(url_for('design.detail', id=id))

    return render_template('design/create.html', form=form, design=design)

@design_bp.route('/<int:id>/delete', methods=['POST'])
@login_required
def delete(id):
    design = Design.query.get_or_404(id)
    if design.user_id != current_user.id:
        flash('您没有权限删除此设计案例！', 'danger')
        return redirect(url_for('design.detail', id=id))

    db.session.delete(design)
    db.session.commit()
    flash('设计案例已删除！', 'success')
    return redirect(url_for('design.index')) 